﻿using Farming.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

namespace Farming.Repositories
{
    public class Repository<T> where T : class
    {
        private readonly FarmingDbContext db;

        public Repository(FarmingDbContext db)
        {
            this.db = db;
        }
        public virtual async Task<int> InsertAsync(T entity)
           
        {
            await db.Set<T>().AddAsync(entity);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 查询所有数据
        /// </summary>
        /// <returns></returns>
        public virtual async Task<List<T>> GetAllAsync()
        {
           return await db.Set<T>().ToListAsync();

        }
        /// <summary>
        /// 查询所有数据
        /// </summary>
        /// <param name="expression">lambda表达式</param>
        /// <returns></returns>
        public virtual async Task<IList<T>> GetAllAsync(Expression<Func<T, bool>> exception)
        {
            return await db.Set<T>().Where(exception).ToListAsync();
        }
        /// <summary>
        /// 获取单个对象
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public virtual async Task<T> GetAsync(int Id)
        {
            return await db.Set<T>().FindAsync(Id);
        }
        /// <summary>
        /// 获取单个对象(通过条件)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual async Task<T> GetAsync(Expression<Func<T, bool>> expression)
        {
            return await db.Set<T>().Where(expression).FirstOrDefaultAsync();
        }
        public async Task<bool> UpdateDataAsync(T eneity)
        {
            db.Set<T>().Update(eneity);
            return await db.SaveChangesAsync()>0;
        }



    }
}